package com.ms.support.domain;


import com.ms.support.jpa.SaveListener;
import com.ms.support.jpa.UserDetailsService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import java.util.Date;


@Component
public class SaveListenerImpl implements SaveListener, ApplicationContextAware {
    protected static final Logger LOG = LoggerFactory.getLogger(SaveListenerImpl.class);

    private static UserDetailsService userDetailsService;

    @PostConstruct
    public void init() {
        userDetailsService = appCtx.getBean(UserDetailsService.class);
        LOG.info("Initializing user service:", userDetailsService);
    }

    @PrePersist
    public void onPersist(Object entity) {
        UserDetails userDetails = null;
        if (entity instanceof IdentifiedAuditableDomainObject && ((IdentifiedAuditableDomainObject) entity).isAuditable()) {
            if (userDetails == null) {
                userDetails = userDetailsService.getUserDetails();
                if (userDetails == null) {
                    throw new IllegalStateException("Error obteniendo informacion de seguridad del usuario");
                }
            }
            IdentifiedAuditableDomainObject auditable = (IdentifiedAuditableDomainObject) entity;
            if(userDetails==null){
                auditable.setCreadoPor("TEST");
            }else{
                auditable.setCreadoPor(userDetails.getUsername());
            }
            auditable.setFechaCreacion(new Date());
        }
    }

    @PreUpdate
    public void onUpdate(Object entity) {
        if (entity instanceof IdentifiedAuditableDomainObject && ((IdentifiedAuditableDomainObject) entity).isAuditable()) {
            UserDetails userDetails = userDetailsService.getUserDetails();
            if (userDetails == null) {
                throw new IllegalStateException("Error obteniendo informacion de seguridad del usuario");
            }


        }
    }

    static ApplicationContext appCtx;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        appCtx = applicationContext;
    }
}

